import { GetDatasetTreeItem, GetTargetTree } from '@/common/types';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import { CaretRightOutlined } from '@ant-design/icons';
import { Button, Tooltip } from 'antd';
import React, { useEffect, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

interface Props {
  treeData: GetDatasetTreeItem[];
  selectData?: GetDatasetTreeItem;
  handleClickUserTree: (treeData: GetDatasetTreeItem, type?: boolean) => void;
  expandedKeys: string[];
  title?: string;
  routerPath: string;
}

interface TreeNodeProps {
  treeData: GetDatasetTreeItem;
  selectData?: GetDatasetTreeItem;
  level?: number;
  handleClickUserTree: (treeData: GetDatasetTreeItem, type?: boolean) => void;
  expandedKeys: string[];
}

const TreeNode = ({
  treeData,
  level = 0,
  handleClickUserTree,
  selectData,
  expandedKeys,
}: TreeNodeProps) => {
  const icon = useMemo(() => {
    if (treeData.type === 'function') {
      return {
        icon: 'file-api',
        color: '#33ADFF',
      };
    } else if (treeData.type === 'folder') {
      return {
        icon: 'folder-svg',
        color: '#FECA27',
      };
    } else {
      return {
        icon: 'dataset',
        color: '#4172FE',
      };
    }
  }, [treeData]);

  const selectStatus = useMemo(() => selectData?._id === treeData._id, [selectData]);
  const isExpanded = useMemo(
    () => expandedKeys.includes(treeData._id),
    [expandedKeys, treeData._id],
  );
  const hasTargets = useMemo(() => treeData?.targets?.length > 0, [treeData]);

  return (
    <>
      <div
        className={`flex h-10 cursor-pointer items-center justify-between rounded-xl ${selectStatus ? 'bg-@brand-color-light' : ''
          }`}
        style={{
          paddingLeft: `${level * 16}px`,
        }}
        onClick={() => handleClickUserTree(treeData)}
      >
        <div
          className={`flex items-center gap-1 ${selectStatus ? ' text-@brand-color' : 'text-[#1d1d1d]'
            } `}
        >
          <div className="flex h-5 w-5 items-center justify-center">
            {treeData?.children?.length > 0 && (
              <CaretRightOutlined
                rotate={isExpanded ? 90 : 0}
                onClick={(e) => {
                  e.stopPropagation();
                  handleClickUserTree(treeData, true);
                }}
              />
            )}
          </div>
          <SvgIcon icon={icon.icon} color={icon.color} size="24px" />
          <span>{treeData.name}</span>
        </div>
        <div className="flex items-end gap-2 pr-2">
          <Tooltip title={hasTargets ? '已配置人员/组织' : '未配置人员/组织'}>
            <div className="flex items-center justify-between">
              <SvgIcon
                icon={hasTargets ? 'user-select' : 'user-not'}
                size={20}
              // color={`${'#D6DBE3'}`}
              />
            </div>
          </Tooltip>
        </div>
      </div>
      {isExpanded &&
        treeData.children &&
        treeData.children.map((item) => (
          <TreeNode
            treeData={item}
            level={level + 1}
            key={item._id}
            handleClickUserTree={handleClickUserTree}
            selectData={selectData}
            expandedKeys={expandedKeys}
          />
        ))}
    </>
  );
};

const LeftTreeUI = ({
  treeData,
  handleClickUserTree,
  selectData,
  expandedKeys,
  title,
  routerPath,
}: Props) => {
  const navigate = useNavigate();
  const location = useLocation();

  const handleClick = () => {
    // 解析 search 参数
    const searchParams = new URLSearchParams(location.search);

    // 移除所有 app 参数
    searchParams.delete('app');

    // 添加新的 app 参数
    searchParams.append('app', routerPath);

    // 如果有 currentTab 字段，改为 knowledge
    if (searchParams.has('currentTab')) {
      searchParams.set('currentTab', 'knowledge');
    }

    // 重新拼接 search 字符串
    const newSearch = `?${searchParams.toString()}`;

    // 拼接新地址
    const newPath = `${location.pathname.replace(/\/$/, '')}${newSearch}`;
    navigate(newPath);
  };

  return (
    <div
      style={{
        minHeight: 'calc(30% - 32px)',
      }}
    >
      <div className=" border-b border-solid border-b-line-1 py-2 pl-4 text-xs font-medium text-text-3">
        {title}
      </div>

      {treeData.length > 0 ? (
        treeData.map((item) => (
          <TreeNode
            treeData={item}
            key={item._id}
            handleClickUserTree={handleClickUserTree}
            selectData={selectData}
            expandedKeys={expandedKeys}
          />
        ))
      ) : (
        <div
          style={{
            height: 'calc(30% - 32px)',
          }}
        >
          <NotData
            fontText={
              <div className="flex flex-col items-center justify-center gap-6">
                <div>暂无{title}</div>
                <div>
                  <Button onClick={handleClick}>去添加</Button>
                </div>
              </div>
            }
          />
        </div>
      )}
    </div>
  );
};

export default LeftTreeUI;
